<template>
    <view class="container">
        <view class="header">
            <view class="back-btn" @click="goBack">
                <text class="back-icon">←</text>
            </view>
            <text class="title">画板</text>
            <view class="actions">
                <button class="action-btn" @click="importImage">导入图片</button>
                <button class="action-btn" @click="clearCanvas">清空</button>
                <button class="action-btn" @click="saveDrawing">保存</button>
            </view>
        </view>

        <view class="toolbar">
            <view class="tool-item" :class="{ active: isDrawingMode }" @click="toggleDrawingMode">
                <text>画笔</text>
            </view>
            <view class="tool-item" :class="{ active: !isDrawingMode }" @click="toggleDrawingMode">
                <text>移动</text>
            </view>
        </view>

        <scroll-view class="content" scroll-y :scroll-with-animation="false" :enable-flex="true"
            :scroll-anchoring="true">
            <canvas class="drawing-board" canvas-id="drawingBoard" @touchstart="touchStart" @touchmove="touchMove"
                @touchend="touchEnd" :disable-scroll="isDrawingMode"></canvas>
        </scroll-view>
    </view>
</template>

<script>
export default {
    data() {
        return {
            ctx: null,
            points: [],
            isDrawing: false,
            lastX: 0,
            lastY: 0,
            isDrawingMode: true,
            imageInfo: null,
            selectedImage: null,
            isResizing: false,
            resizeDirection: null,
            touchStartX: 0,
            touchStartY: 0,
            touchStartWidth: 0,
            touchStartHeight: 0,
            touchStartOffsetX: 0,
            touchStartOffsetY: 0,
            paths: [] // 存储所有绘制路径
        };
    },
    onReady() {
        this.ctx = uni.createCanvasContext('drawingBoard', this, {
            willReadFrequently: true
        });
        this.ctx.setStrokeStyle('#000000');
        this.ctx.setLineWidth(2);
        this.ctx.setLineCap('round');
        this.ctx.setLineJoin('round');
    },
    methods: {
        toggleDrawingMode() {
            this.isDrawingMode = !this.isDrawingMode;
            this.selectedImage = null;
            this.redrawCanvas();
        },
        touchStart(e) {
            if (this.isDrawingMode) {
                this.isDrawing = true;
                const { x, y } = e.touches[0];
                this.lastX = x;
                this.lastY = y;
                this.ctx.beginPath();
                this.ctx.moveTo(x, y);
                this.ctx.stroke();
                this.ctx.draw(true);

                // 开始新的路径
                this.paths.push({
                    points: [{ x, y }],
                    color: '#000000',
                    width: 2
                });
                return;
            }

            const { x, y } = e.touches[0];
            this.touchStartX = x;
            this.touchStartY = y;

            if (this.imageInfo) {
                const { width, height } = this.imageInfo;
                const scaledWidth = width * this.imageInfo.scale;
                const scaledHeight = height * this.imageInfo.scale;

                // 检查是否点击在图片上
                if (x >= this.imageInfo.offsetX && x <= this.imageInfo.offsetX + scaledWidth &&
                    y >= this.imageInfo.offsetY && y <= this.imageInfo.offsetY + scaledHeight) {

                    // 检查是否点击在边缘
                    const edgeSize = 20; // 边缘检测范围
                    if (x <= this.imageInfo.offsetX + edgeSize) {
                        this.isResizing = true;
                        this.resizeDirection = 'left';
                    } else if (x >= this.imageInfo.offsetX + scaledWidth - edgeSize) {
                        this.isResizing = true;
                        this.resizeDirection = 'right';
                    } else if (y <= this.imageInfo.offsetY + edgeSize) {
                        this.isResizing = true;
                        this.resizeDirection = 'top';
                    } else if (y >= this.imageInfo.offsetY + scaledHeight - edgeSize) {
                        this.isResizing = true;
                        this.resizeDirection = 'bottom';
                    } else {
                        this.selectedImage = this.imageInfo;
                        this.touchStartOffsetX = this.imageInfo.offsetX;
                        this.touchStartOffsetY = this.imageInfo.offsetY;
                    }

                    this.touchStartWidth = scaledWidth;
                    this.touchStartHeight = scaledHeight;
                }
            }
        },
        touchMove(e) {
            if (this.isDrawingMode) {
                if (!this.isDrawing) return;
                const { x, y } = e.touches[0];

                // 使用贝塞尔曲线优化绘制效果
                const midX = (this.lastX + x) / 2;
                const midY = (this.lastY + y) / 2;

                this.ctx.quadraticCurveTo(
                    this.lastX,
                    this.lastY,
                    midX,
                    midY
                );

                this.ctx.stroke();
                this.ctx.draw(true);

                // 记录路径点
                if (this.paths.length > 0) {
                    this.paths[this.paths.length - 1].points.push({ x, y });
                }

                this.lastX = x;
                this.lastY = y;
                return;
            }

            if (!this.imageInfo) return;

            const { x, y } = e.touches[0];
            const deltaX = x - this.touchStartX;
            const deltaY = y - this.touchStartY;

            if (this.isResizing) {
                const { width, height } = this.imageInfo;
                let newScale = this.imageInfo.scale;

                switch (this.resizeDirection) {
                    case 'left':
                        newScale = (this.touchStartWidth - deltaX) / width;
                        if (newScale > 0.1) {
                            this.imageInfo.scale = newScale;
                            this.imageInfo.offsetX = this.touchStartOffsetX + deltaX;
                        }
                        break;
                    case 'right':
                        newScale = (this.touchStartWidth + deltaX) / width;
                        if (newScale > 0.1) {
                            this.imageInfo.scale = newScale;
                        }
                        break;
                    case 'top':
                        newScale = (this.touchStartHeight - deltaY) / height;
                        if (newScale > 0.1) {
                            this.imageInfo.scale = newScale;
                            this.imageInfo.offsetY = this.touchStartOffsetY + deltaY;
                        }
                        break;
                    case 'bottom':
                        newScale = (this.touchStartHeight + deltaY) / height;
                        if (newScale > 0.1) {
                            this.imageInfo.scale = newScale;
                        }
                        break;
                }
            } else if (this.selectedImage) {
                this.imageInfo.offsetX = this.touchStartOffsetX + deltaX;
                this.imageInfo.offsetY = this.touchStartOffsetY + deltaY;
            }

            this.redrawCanvas();
        },
        touchEnd() {
            this.isDrawing = false;
            this.isResizing = false;
            this.resizeDirection = null;
        },
        clearCanvas() {
            this.ctx.clearRect(0, 0, 750, 1000);
            this.ctx.draw(true);
            this.imageInfo = null;
            this.selectedImage = null;
            this.paths = []; // 清空路径记录
        },
        redrawCanvas() {
            this.ctx.clearRect(0, 0, 750, 1000);

            // 如果有图片，先绘制图片
            if (this.imageInfo) {
                const { width, height } = this.imageInfo;
                const scaledWidth = width * this.imageInfo.scale;
                const scaledHeight = height * this.imageInfo.scale;

                this.ctx.drawImage(
                    this.imageInfo.path,
                    this.imageInfo.offsetX,
                    this.imageInfo.offsetY,
                    scaledWidth,
                    scaledHeight
                );

                // 如果图片被选中，绘制边框和缩放图标
                if (this.selectedImage === this.imageInfo) {
                    this.ctx.setStrokeStyle('#4CAF50');
                    this.ctx.setLineWidth(2);
                    this.ctx.strokeRect(
                        this.imageInfo.offsetX,
                        this.imageInfo.offsetY,
                        scaledWidth,
                        scaledHeight
                    );

                    // 绘制四个角的缩放图标
                    const iconSize = 20;
                    const iconColor = '#4CAF50';
                    const iconLineWidth = 3;

                    // 左上角
                    this.ctx.setStrokeStyle(iconColor);
                    this.ctx.setLineWidth(iconLineWidth);
                    this.ctx.beginPath();
                    this.ctx.moveTo(this.imageInfo.offsetX, this.imageInfo.offsetY + iconSize);
                    this.ctx.lineTo(this.imageInfo.offsetX, this.imageInfo.offsetY);
                    this.ctx.lineTo(this.imageInfo.offsetX + iconSize, this.imageInfo.offsetY);
                    this.ctx.stroke();

                    // 右上角
                    this.ctx.beginPath();
                    this.ctx.moveTo(this.imageInfo.offsetX + scaledWidth - iconSize, this.imageInfo.offsetY);
                    this.ctx.lineTo(this.imageInfo.offsetX + scaledWidth, this.imageInfo.offsetY);
                    this.ctx.lineTo(this.imageInfo.offsetX + scaledWidth, this.imageInfo.offsetY + iconSize);
                    this.ctx.stroke();

                    // 左下角
                    this.ctx.beginPath();
                    this.ctx.moveTo(this.imageInfo.offsetX, this.imageInfo.offsetY + scaledHeight - iconSize);
                    this.ctx.lineTo(this.imageInfo.offsetX, this.imageInfo.offsetY + scaledHeight);
                    this.ctx.lineTo(this.imageInfo.offsetX + iconSize, this.imageInfo.offsetY + scaledHeight);
                    this.ctx.stroke();

                    // 右下角
                    this.ctx.beginPath();
                    this.ctx.moveTo(this.imageInfo.offsetX + scaledWidth - iconSize, this.imageInfo.offsetY + scaledHeight);
                    this.ctx.lineTo(this.imageInfo.offsetX + scaledWidth, this.imageInfo.offsetY + scaledHeight);
                    this.ctx.lineTo(this.imageInfo.offsetX + scaledWidth, this.imageInfo.offsetY + scaledHeight - iconSize);
                    this.ctx.stroke();
                }
            }

            // 重新绘制所有路径
            this.ctx.setStrokeStyle('#000000');
            this.ctx.setLineWidth(2);
            this.ctx.setLineCap('round');
            this.ctx.setLineJoin('round');

            this.paths.forEach(path => {
                this.ctx.beginPath();
                this.ctx.moveTo(path.points[0].x, path.points[0].y);

                for (let i = 1; i < path.points.length; i++) {
                    const midX = (path.points[i - 1].x + path.points[i].x) / 2;
                    const midY = (path.points[i - 1].y + path.points[i].y) / 2;
                    this.ctx.quadraticCurveTo(
                        path.points[i - 1].x,
                        path.points[i - 1].y,
                        midX,
                        midY
                    );
                }

                this.ctx.stroke();
            });

            this.ctx.draw(true);
        },
        importImage() {
            uni.chooseImage({
                count: 1,
                success: (res) => {
                    const tempFilePath = res.tempFilePaths[0];
                    uni.getImageInfo({
                        src: tempFilePath,
                        success: (info) => {
                            const screenWidth = uni.getSystemInfoSync().windowWidth;
                            const scale = screenWidth / info.width;
                            const height = info.height * scale;

                            this.imageInfo = {
                                path: tempFilePath,
                                width: screenWidth,
                                height: height,
                                scale: 1,
                                offsetX: 0,
                                offsetY: 0
                            };

                            this.redrawCanvas();
                        },
                        fail: (err) => {
                            console.error('获取图片信息失败:', err);
                            uni.showToast({
                                title: '获取图片信息失败',
                                icon: 'none'
                            });
                        }
                    });
                },
                fail: (err) => {
                    console.error('选择图片失败:', err);
                    uni.showToast({
                        title: '选择图片失败',
                        icon: 'none'
                    });
                }
            });
        },
        saveDrawing() {
            // 先重绘画布，确保所有内容都在画布上
            this.redrawCanvas();

            // 延迟一下，确保画布内容已经更新
            setTimeout(() => {
                uni.canvasToTempFilePath({
                    canvasId: 'drawingBoard',
                    success: (res) => {
                        const tempFilePath = res.tempFilePath;
                        // 将临时文件保存到本地
                        uni.saveFile({
                            tempFilePath: tempFilePath,
                            success: (saveRes) => {
                                const savedFilePath = saveRes.savedFilePath;

                                // 获取当前任务列表
                                const tasks = uni.getStorageSync('tasks') ? JSON.parse(uni.getStorageSync('tasks')) : [];

                                // 添加新任务
                                tasks.unshift({
                                    content: '绘画笔记',
                                    completed: false,
                                    image: savedFilePath,
                                    type: 'drawing',
                                    timestamp: new Date().getTime()
                                });

                                // 保存到本地存储
                                uni.setStorageSync('tasks', JSON.stringify(tasks));

                                // 触发主页更新
                                uni.$emit('tasksUpdated');

                                uni.showToast({
                                    title: '保存成功',
                                    icon: 'success',
                                    duration: 1500,
                                    success: () => {
                                        // 延迟返回，让用户看到保存成功的提示
                                        setTimeout(() => {
                                            uni.navigateBack();
                                        }, 1500);
                                    }
                                });
                            },
                            fail: (err) => {
                                console.error('保存文件失败:', err);
                                uni.showToast({
                                    title: '保存失败',
                                    icon: 'none'
                                });
                            }
                        });
                    },
                    fail: (err) => {
                        console.error('生成图片失败:', err);
                        uni.showToast({
                            title: '保存失败',
                            icon: 'none'
                        });
                    }
                });
            }, 100);
        },
        goBack() {
            uni.navigateBack();
        }
    }
};
</script>

<style>
.container {
    padding: 0;
    background-color: #f0f7e6;
    min-height: 100vh;
}

.header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20rpx 30rpx;
    background-color: #f0f7e6;
    position: sticky;
    top: 0;
    z-index: 100;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.back-btn {
    width: 80rpx;
    height: 80rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #fff;
    border-radius: 50%;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.back-icon {
    font-size: 40rpx;
    color: #333;
}

.title {
    flex: 1;
    text-align: center;
    font-size: 36rpx;
    color: #333;
    font-weight: bold;
}

.actions {
    display: flex;
    gap: 20rpx;
}

.action-btn {
    padding: 15rpx 30rpx;
    background-color: #4CAF50;
    color: #fff;
    border-radius: 40rpx;
    font-size: 28rpx;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.toolbar {
    display: flex;
    gap: 20rpx;
    margin: 20rpx 30rpx;
    padding: 10rpx;
    background-color: #fff;
    border-radius: 40rpx;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.tool-item {
    flex: 1;
    padding: 15rpx 0;
    text-align: center;
    background-color: transparent;
    border-radius: 30rpx;
    font-size: 28rpx;
    color: #333;
    transition: all 0.3s;
}

.tool-item.active {
    background-color: #4CAF50;
    color: #fff;
}

.content {
    height: calc(100vh - 240rpx);
    padding: 0 30rpx;
}

.drawing-board {
    width: 100%;
    height: 100%;
    background-color: #fff;
    border-radius: 20rpx;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}
</style>